//
//  SettingView.swift
//  GreenDeal
//
//  Created by Moennig Q on 9/12/2022.
//

import UIKit
import SnapKit
import RxCocoa
import RxSwift
enum SettingCellType: Int {
    case header = 1
    case cell
}
enum SettingMenuType: Int {
    case password = 1
    case loginMethod
    case displayZoom
    case deleteAccount
    case privacyPolicy
    case termsAndCondition
    case versionInfo
    case clearCache
    case logOut
    case none
}
struct SettingViewModel {
    var cellType: SettingCellType = .header
    var menuType: SettingMenuType = .none
    var title: String = ""
    var content: String = ""
    var hideLineViewFlag: Bool = false
}
class SettingView: MeModelVCBaseView {
    lazy var disposeBag = DisposeBag()
    var list = [SettingViewModel]()
    let latestVersionLabel = ContentLabel(R.font.interMedium(size: 15),text: R.string.localizable.theLatestVersion())
    let tableView = TableView()
    var clearCacheClosure: (()->Void)?
    var latestVersionClosure: (()->Void)?
    var deleteAccountClosure: (()->Void)?
    var changePwdClosure: (()->Void)?
    var loginMethodClosure: (()->Void)?
    var privacyPolicyClosure: (()->Void)?
    var termsAndConditionClosure: (()->Void)?
    var clearCacheContent: ContentLabel!
    //
    var tableViewHeightConstraint: Constraint?
    override func setUpviews() {
        //背景颜色
        let contentView = View(hexStr: Constant.SystemBackColor)
        self.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.top.equalTo(topBackView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        tableView.backgroundColor = UIColor(hexStr: Constant.SystemBackColor)
        contentView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(topBackView.snp.bottom)
            self.tableViewHeightConstraint = make.height.greaterThanOrEqualTo(0).constraint
            make.left.right.equalToSuperview()
            make.bottom.lessThanOrEqualToSuperview()
        }
        //
        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 60
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(SettingSectionTableViewCell.self, forCellReuseIdentifier: SettingSectionTableViewCell.reuseCellIdentifier)
        tableView.register(SettingContentTableViewCell.self, forCellReuseIdentifier: SettingContentTableViewCell.reuseCellIdentifier)
        tableView.register(SettingDisplayTableViewCell.self, forCellReuseIdentifier: SettingDisplayTableViewCell.reuseCellIdentifier)
        tableView.register(SettingLogoutTableViewCell.self, forCellReuseIdentifier: SettingLogoutTableViewCell.reuseCellIdentifier)
        //监听tableview的高度
        tableView.rx.observe(CGSize.self,"contentSize").subscribe {[weak self] (size) in
            guard let contentSize = size else {return}
            self?.tableViewHeightConstraint?.update(offset: contentSize.height)
        }.disposed(by: self.disposeBag)
    }
    
    //MAKR: -刷新行
    private func reloadRowByMenuType( _ menuType: SettingMenuType){
        if let index = self.list.firstIndex(where: {$0.menuType == menuType}) {
            self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: UITableView.RowAnimation.none)
        }
    }
}

extension SettingView: UITableViewDataSource, UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let viewModel = self.list[indexPath.row]
        if viewModel.menuType == .logOut {//logout
            var cell = tableView.dequeueReusableCell(withIdentifier: SettingLogoutTableViewCell.reuseCellIdentifier) as? SettingLogoutTableViewCell
            if cell == nil {
                cell = SettingLogoutTableViewCell(style: .default, reuseIdentifier: SettingLogoutTableViewCell.reuseCellIdentifier)
            }
            return cell!
        }else if viewModel.menuType == .displayZoom {//display zoom
            var cell = tableView.dequeueReusableCell(withIdentifier: SettingDisplayTableViewCell.reuseCellIdentifier) as? SettingDisplayTableViewCell
            if cell == nil {
                cell = SettingDisplayTableViewCell(style: .default, reuseIdentifier: SettingDisplayTableViewCell.reuseCellIdentifier)
            }
            cell!.switchDisplayZoomClosure = {[weak self] in
                self?.reloadRowByMenuType(.versionInfo)//此处不能直接刷新display zoom row，因为会导致点击无效
            }
            cell!.setDisplayZoomSetting()
            return cell!
        }else if viewModel.cellType == .header{
            var cell = tableView.dequeueReusableCell(withIdentifier: SettingSectionTableViewCell.reuseCellIdentifier) as? SettingSectionTableViewCell
            if cell == nil {
                cell = SettingSectionTableViewCell(style: .default, reuseIdentifier: SettingSectionTableViewCell.reuseCellIdentifier)
            }
            cell?.setData(self.list[indexPath.row])
            
            return cell!
        }else{//cell
            var cell = tableView.dequeueReusableCell(withIdentifier: SettingContentTableViewCell.reuseCellIdentifier) as? SettingContentTableViewCell
            if cell == nil {
                cell = SettingContentTableViewCell(style: .default, reuseIdentifier: SettingContentTableViewCell.reuseCellIdentifier)
            }
            cell?.setData(self.list[indexPath.row])
            
            return cell!
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let viewModel = self.list[indexPath.row]
        switch viewModel.menuType {
        case .password:
            self.changePwdClosure?()
        case .loginMethod:
            self.loginMethodClosure?()
        case .privacyPolicy:
            self.privacyPolicyClosure?()
        case .termsAndCondition:
            self.termsAndConditionClosure?()
        case .versionInfo:
            self.latestVersionClosure?()
        case .clearCache:
            self.clearCacheClosure?()
        case .deleteAccount:
            self.deleteAccountClosure?()
        case .logOut:
            LoginService.logOut()
        default:
            break
        }
    }
}

class SettingSectionTableViewCell: TableViewCell{
    let titleLabel = ContentLabel(R.font.interRegular(size: 12),hexStr: "#292D3299")
    override func setUpviews() {
        self.backgroundColor = UIColor(hexStr: Constant.SystemBackColor)
        self.contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(15)
            make.left.equalTo(Constant.AllOutMargin)
            make.height.width.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-8)
        }
    }
    func setData(_ viewModel: SettingViewModel){
        self.titleLabel.text = viewModel.title
    }
}
class SettingContentTableViewCell: TableViewCell{
    let titleLabel = ContentLabel(R.font.interSemiBold(size: 15))
    let contentLabel = ContentLabel(R.font.interMedium(size: 15))
    let moreImageView = ViewFactory.shared.generateMoreImageView()
    let lineView = View(hexStr: Constant.SeparatorColorHexStr)
    override func setUpviews() {
        self.backgroundColor = .white
        titleLabel.numberOfLines = 0
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.left.equalTo(Constant.AllOutMargin)
            make.height.width.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-10)
        }
        //more image
        contentView.addSubview(moreImageView)
        moreImageView.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.right).offset(5)
            make.right.equalTo(-Constant.AllOutMargin)
            make.centerY.equalTo(titleLabel)
            make.width.height.equalTo(24)
        }
        //content label
        contentLabel.textColor = UIColor(hexStr: "#379657")
        contentView.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.center.equalTo(moreImageView)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //
        contentView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
    }
    func setData(_ viewModel: SettingViewModel){
        self.titleLabel.text = viewModel.title
        self.moreImageView.isHidden = viewModel.content == "" ? false: true
        self.contentLabel.text = viewModel.content
        self.lineView.isHidden = viewModel.hideLineViewFlag
    }
}
class SettingDisplayTableViewCell: TableViewCell{
    var switchDisplayZoomClosure: (()->Void)?
    let titleLabel = ContentLabel(R.font.interSemiBold(size: 15))
    let standardViewButton = LayoutButton(.left,at: 12)
    let magnifiedViewButton = LayoutButton(.left,at: 12)
    override func setUpviews() {
        self.backgroundColor = .white
        self.titleLabel.text = "Display Zoom"
        self.contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.left.equalTo(Constant.AllOutMargin)
            make.height.width.greaterThanOrEqualTo(0)
            if APPConfig.WidthForPortrait > 320 {
                make.bottom.equalTo(-10)
            }
        }
        //standardViewButton
        standardViewButton.disableScaleFlag()//字号保持不变
        standardViewButton.setBtnInfo(FontScaleParam.standard.rawValue, hexStr: "#292D32", textFont: R.font.interMedium(size: 14), imageName: "me_switch_view_sel")
        contentView.addSubview(standardViewButton)
        standardViewButton.snp.makeConstraints { make in
            make.centerY.equalTo(titleLabel)
            make.left.equalTo(titleLabel.snp.right).offset(20)
            make.size.greaterThanOrEqualTo(0)
        }
        //Magnified ViewButton
        magnifiedViewButton.disableScaleFlag()//字号保持不变
        magnifiedViewButton.setBtnInfo(FontScaleParam.larger.rawValue, hexStr: "#292D32", textFont: R.font.interMedium(size: 16.8), imageName: "me_switch_view_unsel")
        contentView.addSubview(magnifiedViewButton)
        if APPConfig.WidthForPortrait > 320 {//
            magnifiedViewButton.snp.makeConstraints { make in
                make.left.equalTo(standardViewButton.snp.right).offset(20)
                make.size.greaterThanOrEqualTo(0)
                make.centerY.equalTo(standardViewButton)
            }
        }else{//320的，liang
            magnifiedViewButton.snp.makeConstraints { make in
                make.top.equalTo(standardViewButton.snp.bottom).offset(5)
                make.left.equalTo(standardViewButton)
                make.size.greaterThanOrEqualTo(0)
                make.bottom.equalTo(-8)
            }
        }
        standardViewButton.rx.tap.subscribe { [weak self] _ in
            guard let strongSelf = self else {return}
            if Constant.standardViewFlag == false{
                Constant.standardViewFlag = true
                strongSelf.setDisplayZoomSetting()
                strongSelf.switchDisplayZoomClosure?()
            }
        }.disposed(by: self.disposeBag)
        magnifiedViewButton.rx.tap.subscribe { [weak self] _ in
            guard let strongSelf = self else {return}
            if Constant.standardViewFlag {
                Constant.standardViewFlag = false
                strongSelf.setDisplayZoomSetting()
                strongSelf.switchDisplayZoomClosure?()
            }
        }.disposed(by: self.disposeBag)
    }
    //MAKR: - 初始化设置
    func setDisplayZoomSetting(){
        magnifiedViewButton.setImage((Constant.standardViewFlag ? R.image.me_switch_view_unsel() : R.image.me_switch_view_sel()), for: UIControl.State.normal)
        standardViewButton.setImage((Constant.standardViewFlag ? R.image.me_switch_view_sel() : R.image.me_switch_view_unsel()), for: UIControl.State.normal)
    }
}
//Logout cell
class SettingLogoutTableViewCell: TableViewCell{
    let titleLabel = ContentLabel(R.font.interSemiBold(size: 15),text: R.string.localizable.logOut(),hexStr: Constant.ThemeColorHexStr)
    override func setUpviews() {
        self.backgroundColor = UIColor(hexStr: Constant.SystemBackColor)
        titleLabel.textAlignment = .center
        titleLabel.backgroundColor = .white
        self.contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(34)
            make.left.right.equalToSuperview()
            make.height.equalTo(42)
            make.bottom.equalToSuperview()
        }
    }
}
